package com.jd.tuning;

import java.math.BigDecimal;

/**
 * 金额工具类
 */
public class MoneyUtils {

    /**金额为分的格式 */
    public static final String CURRENCY_FEN_REGEX = "\\-?[0-9]+";


    /**
     * 将分为单位的转换为元 （除100）
     *
     * @param amount
     * @return
     * @throws Exception
     */
    public static Integer changeF2Y(String amount) throws Exception{
        if(!amount.matches(CURRENCY_FEN_REGEX)) {
            throw new Exception("金额格式有误");
        }
        return BigDecimal.valueOf(Long.valueOf(amount)).divide(new BigDecimal(100)).intValue();
    }


    /**
     * 将元为单位的转换为分 替换小数点，支持以逗号区分的金额
     *
     * @param amount
     * @return
     */
    public static Integer changeY2F(String amount){
        String currency =  amount.replaceAll("\\$|\\￥|\\,", "");  //处理包含, ￥ 或者$的金额
        int index = currency.indexOf(".");
        int length = currency.length();
        Integer amLong = 0;
        if(index == -1){
            amLong = Integer.valueOf(currency+"00");
        }else if(length - index >= 3){
            amLong = Integer.valueOf((currency.substring(0, index+3)).replace(".", ""));
        }else if(length - index == 2){
            amLong = Integer.valueOf((currency.substring(0, index+2)).replace(".", "")+0);
        }else{
            amLong = Integer.valueOf((currency.substring(0, index+1)).replace(".", "")+"00");
        }
        return amLong;
    }


    public static void main(String[] args) {
        try {
            Integer a = MoneyUtils.changeY2F("0.1");
            System.out.println(a);
            Integer b= MoneyUtils.changeF2Y("100");
            System.out.println(b);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}